package com.qf.filters;

import com.qf.feign.CacheService;
import com.qianfeng.smsplatform.common.constants.CacheConstants;
import com.qianfeng.smsplatform.common.constants.InterfaceExceptionDict;
import com.qianfeng.smsplatform.common.model.Standard_Submit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/*
 * @Data: 2021/7/21 19:46
 * */
@Component
public class FeeFilter implements FiltersChain {

    private CacheService cacheService;
    @Autowired
    public void setCacheService(CacheService cacheService) {
        this.cacheService = cacheService;
    }

    @Override
    public boolean dealSms(Standard_Submit submit) {
//        计费用的过滤器  主要看用户有没有钱
//        每天短信 都需要钱    刻苦需要支付的费用 如果钱不够不让发送
//          先获取到 当前客户 每条短信得钱数    数据在缓存中
        String priceString = cacheService.HGet(CacheConstants.CACHE_PREFIX_ROUTER + submit.getClientID(), "price");

//        判断 价格 是多少  不能小于等于0
        Integer price=0;
        if(StringUtils.isEmpty(priceString)){
            System.out.println("价格有问题");
        }else {
            price = Integer.parseInt(priceString);
//            判断当前的钱是不是够扣 短信费用  通过 给用户减指定得金额   剩余的钱数大于0 代表减成功
            Long money = cacheService.hIncr(CacheConstants.CACHE_PREFIX_CLIENT + submit.getClientID(), "money",0-(long)price );
            System.out.println("获得到得money是："+money);
            if(money>=0){
                System.out.println("扣钱成功");
            }else {
                System.out.println("扣钱失败");
                submit.setReportState(2);
                submit.setErrorCode(InterfaceExceptionDict.RETURN_STATUS_FEE_ERROR);
                submit.setDescription("余额不足");
              cacheService.hIncr(CacheConstants.CACHE_PREFIX_CLIENT + submit.getClientID(), "money",0L+price );

            }
        }

        return true;
    }
}
